package com.itheima.health.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.List;

/**
 * @author ：王玺淦
 * @date ：Created in 2019/6/12
 * @description ：套餐Controller
 * @version: 1.0
 */
@RestController
@RequestMapping("/mobile/setmeal")
public class SetmealController {
	@Reference
	private SetmealService setmealService;

	@Autowired
	JedisPool jedisPool;

	/**
	 * 获取套餐列表数据
	 * @return Result
	 */
	@RequestMapping("/getSetmeal")
	public Result getSetmeal(){
		try{
			//从redis中获取套餐信息
			String setmealList4redis = jedisPool.getResource().get("setmealList4redis");

			if (setmealList4redis==null){
				//在redis获取不到，从MySQL中获取
				List<Setmeal> setmealList = setmealService.findAll();
				//转换成json对象
				String s = JSON.toJSONString(setmealList);
				//存入redis
				jedisPool.getResource().set("setmealList4redis",s);
				//返回结果
				return new Result(true, MessageConst.QUERY_SETMEAL_SUCCESS,setmealList);
			}else{
				//将在redis中获取的json对象转换为List集合
				List<Setmeal> setmealList = JSON.parseArray(setmealList4redis,Setmeal.class);
				//返回结果
				return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,setmealList);
			}

		}catch(Exception e){
			e.printStackTrace();
			return new Result(false,MessageConst.QUERY_SETMEAL_FAIL);
		}
	}

	/**
	 * 根据id获取套餐数据
	 * @param id
	 * @return
	 */
	@RequestMapping("/findById")
	public Result findById(Integer id){
		try{
			//尝试在redis中获取套餐数据
			String setmeal4Redis = jedisPool.getResource().get("setmeal4redis" + id);
			if (setmeal4Redis==null){
				//没获取到在MySQL中获取
				Setmeal setmeal = setmealService.findById(id);
				//转换为json对象
				String s = JSON.toJSONString(setmeal);
				//存入redis
				jedisPool.getResource().set("setmeal4redis"+id,s);
				//返回结果
				return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,setmeal);
			}else{
				//获取到了转换成Setmeal对象
				Setmeal setmeal = JSON.parseObject(setmeal4Redis, Setmeal.class);
				//返回结果
				return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,setmeal);
			}

		}catch(Exception e){
			e.printStackTrace();
			return new Result(false,MessageConst.QUERY_SETMEAL_FAIL);
		}
	}


}
